﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.IO.Packaging;
using System.Threading.Tasks;

namespace TV_Organizer.Helpers
{
    public static class WebHelpers
    {
        public static XDocument GetXmlFromUrl(string url)
        {
            var client = new WebClient();
            var stream = client.OpenRead(url);
            var streamReader = new StreamReader(stream);
            var xmlContent = streamReader.ReadToEnd();

            stream.Close();
            streamReader.Close();

            return XDocument.Parse(xmlContent);
        }

        public static string GetStringFromUrl(string url)
        {
            var client = new WebClient();
            var stream = client.OpenRead(url);
            var streamReader = new StreamReader(stream);
            var xmlContent = streamReader.ReadToEnd();

            stream.Close();
            streamReader.Close();

            return xmlContent;
        }

        public static Stream GetStreamFromUrl(string url)
        {
            var client = new WebClient();
            return client.OpenRead(url);
        }

        public static async Task SaveUrlToFileAsync(string url, string file, FileMode fileMode = FileMode.Create)
        {
            await TaskEx.Run(() =>
            {
                var client = new WebClient();
                var stream = client.OpenRead(url);

                var fstream = new FileStream(file, fileMode);
                stream.CopyTo(fstream);

                fstream.Close();
                stream.Close();
            });
        }

        public static async Task<string> SaveUrlToTempFileAsync(string url)
        {
            var file = System.IO.Path.GetTempFileName();
            await SaveUrlToFileAsync(url, file, FileMode.Append);
            return file;
        }
    }
}
